// 引入创建小仓库的方法
import { defineStore } from "pinia";
import { login, getUser } from "@/api/user";
import type { UserForm } from '@/api/user/type.ts'
import { routeList } from '@/router/routes'
import { setToken, getToken, remoToken } from "@/utils/storage";
let userStorePinia = defineStore('User', {
    state: () => {
        return {
            // token
            token: getToken('token'),
            // 路由
            routerArr: routeList,
            // 用户名
            userName: '',
            // 用户头像
            avatar: '',
        }
    },
    actions: {
        async userLogin(value: UserForm) {
            try {
                let res = await login(value)
                if (res.code == 200) {
                    this.token = res.data.token
                    setToken('token', res.data.token.toString())
                    return res.message
                } else {
                    throw res.message
                }
            } catch (error) {
                throw error;
            }
        },
        async userInfo() {
            try {
                let res = await getUser()
                if (res.code == 200) {
                    this.userName = res.data.username
                    this.avatar = res.data.avatar

                    return res.message
                } else {
                    return Promise.reject(res.message)
                    throw res.message
                }
            } catch (error) {
                throw error.message
            }
        },
        quitUserStore() {
            this.token = ''
            this.userName = ''
            this.avatar = ''
            remoToken('token')
        }
    },
    getters: {}
})

export default userStorePinia